<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTool>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: 16 条</span>
        </template>
        <!-- 插到right插槽位置  -->
        <template #right>
          <el-button v-allow="'import_employee'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </PageTool>
      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop: 'workNumber'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template slot-scope="scope">
              <ImageHolder img :src="scope.row.staffPhoto" />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template slot-scope="scope">
              {{ formatEmployment( scope.row.formOfEmployment ) }}
            </template>
          </el-table-column>

          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(scope.row)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page.sync="curPage"
            layout="total,sizes,prev, pager, next,jumper"
            :total="total"
            :page-size="pageParams.size"
            :page-sizes="[5,4]"
            @current-change="hCurrentChange"
            @size-change="hSizeChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      title="增加员工"
      @close="hClose"
    >
      <addor-edit ref="addorEdit" @close="showDialog=false" @update-empolyee="hUpdateEmpolyee" />
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
      title="角色分配"
    >
      <AssignRole
        ref="assignRole"
        :employee-id="curEmployeId"
        @close="showDialogRole=false"
        @AssignRole="hUpdateClose"
      />
    </el-dialog></div>
</template>
<script>
import AssignRole from './assignRole.vue'
import addorEdit from './empDialog.vue'
// 枚举
import EmployeeEnum from '@/constant/employees'
const hireType = EmployeeEnum.hireType
console.log(hireType)
const EmployeeEnu = hireType.reduce((acc, item) => { return { ...acc, [item.id]: item.value } }, {})
console.log('枚举信息', EmployeeEnum.hireType, hireType)
import { getEmployeeList, delEmployee } from '@/api/employees'
export default {
  name: 'Employee',
  components: {
    addorEdit,
    AssignRole
  },
  data() {
    return {
      curEmployeId: '', // 当前的员工编号
      curPage: 1, // 当前的页码设置给分页组件的
      total: 0,
      list: [],
      showDialog: false,
      showDialogRole: false,
      pageParams: {
        page: 1,
        size: 5
      }
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    formatDate(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })
      // data把list中没一个对象转成对应的value数组
      data = list.map(obj => {
        const key = obj['formOfEmployment']
        obj['formOfEmployment'] = EmployeeEnu[key] // 1或者2
        return Object.values(obj)
      })
      return { header, data }
    },
    // excel导出
    hExport() {
      import('@/vendor/Export2Excel').then(async excel => {
        const res = await getEmployeeList(this.pageParams.page, this.pageParams.size)
        console.log(res)
        // 赋值
        const list = res.data.rows
        console.log('从后端获取的数据', list)
        const { header, data } = this.formatDate(list)
        console.log(header, data)
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: header, // 表头 必填
          data: data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams.page, this.pageParams.size)
        console.log(res)
        // 赋值
        this.total = res.data.total
        // 保存数据。
        this.list = res.data.rows
        this.curPage = this.pageParams.page // 通知分页组件去更新页码数据
      } catch (err) {
        console.log(err)
        this.$message.success('加载失败')
      }
    },
    formatEmployment(num) {
    // 从hireType中 通过id找到对应的元素的value
      // const item = hireType.find(it => it.id === num)
      // if (item) {
      //   return item.value
      // } else {
      //   return '不能确定'
      // }
      return EmployeeEnu[num]
    },
    // 会自动接受当前点击的页码
    hCurrentChange(curPage) {
      this.pageParams.page = curPage
      this.loadEmployeeList()
    },
    // 每页几条
    hSizeChange(curSize) {
      this.pageParams.size = curSize
      // 重新发送请求
      this.loadEmployeeList()
    },
    // 删除
    async doDel(id) {
      try {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        this.$message.success('删除成功')
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page === 0) {
            this.pageParams.page = 1
          }
        }
        // 重新加载数据
        this.loadEmployeeList()
        // 保存数据
      } catch (err) {
        this.$message.success('删除失败')
        console.log('delEmployee', err)
      }
    },
    hDel(id) {
      this.$confirm('你确定要删除吗').then(() => {
        this.doDel(id)
      }).catch(() => {

      })
    },
    // 增加员工
    hAdd() {
      this.showDialog = true
      console.log(this)
    },
    hUpdateEmpolyee() {
      this.showDialog = false
      // 更新表格数据
      // if（最后一页是满的）{
      //   this.page=最大页面+1
      // }else（最后一页不是满的）{
      //   最大页面的下一页
      //   this.page=最后一页的页码
      // }
      // this.total：一共几条16
      // this.size每页显示几条
      if (this.total % this.pageParams.size === 0) {
        this.pageParams.page = (this.total / this.pageParams.size) + 1
        // this.pageParams.page = Math.ceil(this.total / this.pageParams.size) + 1
      } else {
        // this.pageParams.page = Math.ceil(this.total / this.pageParams.size)
        // 最后一页的页码
        this.pageParams.page = Math.floor(this.total / this.pageParams.size) + 1
      }
      this.loadEmployeeList()
    },
    hClose() {
      // 调用子组件中的方法
      this.$refs.addorEdit.resetForm()
    },
    hAssignRole({ id }) {
      console.log(id)
      this.showDialogRole = true
      this.curEmployeId = id
      // 直接找到子组件调用方法获取最新的数据
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
      })
    },
    // 用户分配角色成功
    hUpdateClose() {
      this.showDialogRole = false
      this.loadEmployeeList()
      this.$message.success('分配角色成功')
    }
  }
}
</script>

